package com.learn.xueer.ui.fragment

import android.animation.ValueAnimator
import android.os.Bundle
import android.widget.LinearLayout
import androidx.core.animation.doOnEnd
import androidx.core.view.get
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.viewpager.widget.ViewPager.SimpleOnPageChangeListener
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestOptions
import com.learn.xueer.R
import com.learn.xueer.app.base.BaseFragment1
import com.learn.xueer.app.util.CacheUtil
import com.learn.xueer.data.model.bean.PkResponse
import com.learn.xueer.data.model.bean.QuestionBean
import com.learn.xueer.data.model.bean.WordBean
import com.learn.xueer.databinding.FragmentWordPkAnswerBinding
import com.learn.xueer.ui.adapter.AnswerAdapter
import com.learn.xueer.ui.viewmodel.PkAnswerViewModel
import kotlinx.android.synthetic.main.fragment_word_pk_answer.iv_avatar_user_first
import kotlinx.android.synthetic.main.fragment_word_pk_answer.iv_avatar_user_second
import kotlinx.android.synthetic.main.fragment_word_pk_answer.progress_bar
import kotlinx.android.synthetic.main.fragment_word_pk_answer.tv_name_user_first
import kotlinx.android.synthetic.main.fragment_word_pk_answer.tv_name_user_second
import kotlinx.android.synthetic.main.fragment_word_pk_answer.vp_question
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.util.Random


class PkAnswerFragment : BaseFragment1<PkAnswerViewModel, FragmentWordPkAnswerBinding>() {

    lateinit var pkInfo: PkResponse
    var questions: ArrayList<QuestionBean> = ArrayList()
    val progressAnim = ValueAnimator.ofInt(0, 100)
    var startTime = System.currentTimeMillis()

    override fun initView(savedInstanceState: Bundle?) {
        pkInfo = arguments?.get("pkInfo") as PkResponse
        mViewBind.vm = mViewModel
        CacheUtil.getUser()?.let {
            tv_name_user_first.text = it.nickname
            Glide.with(iv_avatar_user_first)
                .load(it.avatar)
                .apply(RequestOptions.bitmapTransform(CircleCrop()))
                .transition(DrawableTransitionOptions.withCrossFade(500))
                .into(iv_avatar_user_first)
        }
        pkInfo.otherUser.let {
            tv_name_user_second.text = it.nickname
            val avatar = it.avatar
            Glide.with(iv_avatar_user_second)
                .load(avatar)
                .apply(RequestOptions.bitmapTransform(CircleCrop()))
                .transition(DrawableTransitionOptions.withCrossFade(500))
                .into(iv_avatar_user_second)
        }
        pkInfo.wordsList.forEach {
            val questionBean = QuestionBean(-1, -1, -1, ArrayList())
            val words = ArrayList<WordBean>()
            words.add(it)
            it.falseList.forEach { errWord -> words.add(errWord) }
            words.shuffle()
            questionBean.wordsList = words
            questions.add(questionBean)
        }
        val adapter = AnswerAdapter(questions, pkInfo) { position, id, wid ->
            mViewModel.updateScore(questions[position])
            lifecycleScope.launch {
                delay(500)
                if (position == questions.size - 1) { // 最后一题
                    val bundle = Bundle()
                    bundle.putParcelableArrayList("question", questions)
                    bundle.putSerializable("pkInfo", pkInfo)
                    bundle.putSerializable(
                        "interval",
                        (System.currentTimeMillis() - startTime).toInt()
                    )
                    findNavController().navigate(R.id.navToResult, bundle)
                } else {
                    vp_question.currentItem += 1
                }
            }
        }
        vp_question.adapter = adapter
        vp_question.offscreenPageLimit = 5
        vp_question.setOnTouchListener { p0, p1 -> return@setOnTouchListener false }
        progressAnim.addUpdateListener {
            if (isAdded) {
                progress_bar.progress = it.animatedValue as Int
            }
        }
        progressAnim.doOnEnd {
            val question = questions[vp_question.currentItem]
            if (question.hasAnswer == -1) {
                val index = Random().nextInt(question.wordsList.size)
                vp_question.getChildAt(vp_question.currentItem)
                    .findViewById<LinearLayout>(R.id.ll_question).get(index).callOnClick()
            }
        }
        progressAnim.duration = 10000
        progressAnim.start()
        vp_question.addOnPageChangeListener(object : SimpleOnPageChangeListener() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                if (questions[position].hasAnswer == -1) {
                    progress_bar.progress = 0
                    progressAnim.start()
                }
            }
        })
        startTime = System.currentTimeMillis()
    }

    override fun onDestroyView() {
        progressAnim.cancel()
        super.onDestroyView()
    }
}